package ch.zbw.swt.sysventory.network.scan;

import java.util.ArrayList;
import java.util.List;

import ch.zbw.swt.sysventory.hibernate.entity.Computer;
import ch.zbw.swt.sysventory.hibernate.entity.Nic;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public class ScanNic {

	// Init Data Types
	public String nameNic;
	public String ipv4Nic;
	public String ipv6Nic;
	public String macAdressNic;
	public String standardGatewayNic;
	public boolean dhcpNic;
	public String subnetNic;

	private List<Nic> nInterfaces;
	private Computer computer;

	// Constructor
	public ScanNic(Computer computer) {

		this.computer = computer;
		// Create Listobject
		this.nInterfaces = new ArrayList<Nic>();
	}

	public List<Nic> getNic(String host) {
		
		String connectStr = String.format("winmgmts:\\\\%s\\root\\CIMV2", host);
		String query = "SELECT * FROM Win32_NetworkAdapterConfiguration";

		try {
			// Load Librarys
			ActiveXComponent axWMI = new ActiveXComponent(connectStr);

			// Execute the query
			Variant vCollection = axWMI.invoke("ExecQuery", new Variant(query));

			// Das Resultat ist eine Datensammlung
			EnumVariant enumVariant = new EnumVariant(vCollection.toDispatch());
			Dispatch item = null;
			while (enumVariant.hasMoreElements()) {
				item = enumVariant.nextElement().toDispatch();
				// Dispatch.call returns a Variant which we can convert to a
				// java
				// form.
				macAdressNic = Dispatch.call(item, "MACAddress").toString();
				if (macAdressNic != "null") {
					nameNic = Dispatch.call(item, "Description").toString();
					String ip = Dispatch.call(item, "IPAddress").toString();
					if (ip != "null") {
						int index = ip.lastIndexOf(' ');
						if (index == 0) {
							ipv4Nic = ip.trim();
							ipv6Nic = "";
						} else {
							ipv4Nic = ip.substring(0, index).trim();
							ipv6Nic = ip.substring(index, ip.length()).trim();
						}
					}
					standardGatewayNic = Dispatch
							.call(item, "DefaultIPGateway").toString().trim();
					if (standardGatewayNic == "null") {
						standardGatewayNic = "";
					}

					String dhcpNic = Dispatch.call(item, "DHCPEnabled")
							.toString();

					subnetNic = Dispatch.call(item, "IPSubnet").toString()
							.trim();
					if (subnetNic == "null") {
						subnetNic = "";
					}

					Nic nic = new Nic(ipv4Nic, ipv6Nic, nameNic, macAdressNic,
							standardGatewayNic, dhcpNic, subnetNic, computer);
					nInterfaces.add(nic);

				}

			}
		} catch (Exception e) {

		}

		return nInterfaces;

	}
}
